Cloudflare Workers KV
Key-Value store
bindings綁定Worker與KV命名空間的通訊
在wrangler.toml中綁定
code:wrangler.toml
name = "worker"
kv_namespaces = [
{ binding = "TODO", id = "06779da6940b431db6e566b4846d64db", preview_id="06779da6940b431db6e566b484a6a769a7a" }
]
使用env.NAMESPACE.get(key);取得key對應的值
code:javascript
export default {
async fetch(request, env, ctx) {
// Get the value for the "to-do:123" key
// NOTE: Relies on the TODO KV binding that maps to the "My Tasks" namespace.
let value = await env.TODO.get("to-do:123");
// Return the value, as is, for the Response
return new Response(value);
},
};
本地開發時,為了避免影響到上限環境的資料,可改為使用wrangler dev --remote
會改為使用wrangler.toml中以preview_id綁定的KV
wrangler
npx wrangler kv:namespace create TEST_KV
copy ID and paste to wrangler.toml
code:wrangler.toml
kv_namespaces
binding = "TEST_KV"
id = "ID_HERE"
code:index.ts
// 名稱和 binding 相同
const app = new Hono<{
Bindings: { TEST_KV: KVNamespace }
}>();
app.get("/counter", async (c) => {
const key = c.req.query()"key" || "defaultKey"; const count = Number(await c.env.TEST_KV.get(key));
const count = !isNaN(value) ? value + 1 : 1;
// 存入 KV
await c.env.TEST_KV.put(key, String(count));
return c.text(String(count));
});
export default app;
kv.get(key)取值、kv.put(key, value)存值